import java.util.*;

class Solution {
    public int preIdx = 0;
    public int searchIdx(char[] inorder,int left, int right, int val) {
        for (int i = left; i <= right; i++) {
            if (inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }
    public TreeNode creatTree(char[] preorder,char[] inorder,int left, int right) {
        if (left > right) return null;
        TreeNode root = new TreeNode(preorder[preIdx]);
        int inIdx = searchIdx(inorder,left,right,root.val);
        preIdx++;

        root.left = creatTree(preorder,inorder,left,inIdx-1);
        root.right = creatTree(preorder,inorder,inIdx+1,right);

        return root;
    }
    public TreeNode buildTree(char[] preorder, char[] inorder) {
        return creatTree(preorder,inorder,0,preorder.length-1);
    }

    public List<List<Character>> levelOrder(TreeNode root) {
        List<List<Character>> list = new ArrayList<>();
        if (root == null) return list;
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);
        while (!q.isEmpty()){
            int size = q.size();
            List<Character> t = new ArrayList<>();
            for (int i = 0; i < size; i++){
                TreeNode cur = q.poll();
                t.add(cur.val);
                if (cur.left != null) q.offer(cur.left);
                if (cur.right != null) q.offer(cur.right);
            }
            list.add(t);
        }
        return list;
    }

    public List<Character> postorderTraversal(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.empty()){
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if (top.right == null || top.right == prev) {
                prev = top;
                stack.pop();
                list.add(top.val);
            } else {
                cur = top.right;
            }
        }
        return list;
    }

    public static void main(String[] args) {
        char[] pre = {'A','B','D','G','J','E','H','C','F','I','K','L'};
        char[] in = {'D','J','G','B','E','H','A','C','K','I','L','F'};
        Solution solution = new Solution();
        TreeNode tree = solution.buildTree(pre, in);
        solution.levelOrder(tree);
        System.out.println();
        solution.postorderTraversal(tree);
    }
}